package cn.edu.uestc.smgt.controller.yh;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.edu.uestc.smgt.pojo.User;
import cn.edu.uestc.smgt.service.BuzhuTempService;
import cn.edu.uestc.smgt.service.UnitService;
import cn.edu.uestc.smgt.util.ExcelUtil;

@Controller
@RequestMapping("/yh/BZ_tmp/")
public class BuzhuTempController {

	@Autowired
	private UnitService unitService;

	@Autowired
	private BuzhuTempService buzhuTempService;

	/**
	 * 下载补助填写的模板用于上传使用，用户必须按照这个模板上传
	 */
	@RequestMapping("downloadMB")
	public ResponseEntity<byte[]> downloadMB(HttpServletRequest request,
			HttpServletResponse response, HttpSession session)
			throws IOException {
		byte[] body = null;
		InputStream is = request.getSession().getServletContext()
				.getResourceAsStream("/download/moban.xls");
		body = new byte[is.available()];
		is.read(body);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition", "attchement;filename=moban.xls");
		HttpStatus statusCode = HttpStatus.OK;
		ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body,
				headers, statusCode);
		return entity;
	}

	/**
	 * 获取当前未提交的补助记录
	 */
	@RequestMapping("list_WTJ")
	@ResponseBody
	public Object getBuzhuTemp(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		User yh = (User) session.getAttribute("user");
		if (yh == null) {
			return null;
		}
		return buzhuTempService.findAllBuzhuTempWithUnitId(yh.getUnitId());
	}

	/**
	 * 上传补助信息到临时信息表。:excel格式不符无法上传
	 */
	@Transactional(rollbackFor = { Exception.class })
	@RequestMapping("upload")
	@ResponseBody
	public Object upload(HttpServletRequest request,
			HttpServletResponse response, HttpSession session,
			@RequestParam("uploadExcel") CommonsMultipartFile files)
			throws IOException {
		HashMap ret = new HashMap();
		User yh = (User) session.getAttribute("user");
		if (yh == null) {
			ret.put("message", "用户未登录");
			ret.put("status", 0);
			return ret;
		}
		// 获取当前用户的单位编号，单位名称
		String unitId = yh.getUnitId();
		String unitName = unitService.getUnitById(unitId).getName();
		System.out.println(files.getOriginalFilename());
		int fileSize = 0;
		if (files != null) {
			int rowNum = 0;
			try {
				// 将excel文件转为List，然后调用service层方法批量插入
				InputStream is = files.getInputStream();
				HashMap sheetMap = ExcelUtil.getSheet(is, 1);
				if (sheetMap.get("sheet") != null) {
					Sheet sheet = (Sheet) sheetMap.get("sheet");
					// 首先检测上传的excel表格是否符合需要的格式
					String checkString;
					if ((checkString = checkGeShi(sheet)) == null) {
						List list = readData(sheet);
						if (null != list)
							fileSize = list.size();
						// 导入数据，如果有已经存在数据库中的数据则不导入
						for (int i = 0; i < list.size(); i++) {
							HashMap map = (HashMap) list.get(i);
							rowNum = ((Integer) map.get("row")).intValue();
							map.put("unitId", unitId);
							map.put("unitName", unitName);
							buzhuTempService.addWithMap(map);
						}
					} else {
						ret.put("message", checkString);
						return ret;
					}
				} else {
					ret.put("message", "数据为空");
					return ret;
				}
				is.close();
			} catch (Exception e1) {
				e1.printStackTrace();
				if (rowNum == fileSize + 1) {
					ret.put("message", "导入数据成功");
					return ret;
				} else {
					ret.put("message", "第" + rowNum + "行数据异常，请检查！");
					return ret;
				}
			}
			ret.put("message", "导入数据成功");
			return ret;
		} else {
			ret.put("message", "未选择文件！");
			return ret;
		}

	}

	/**
	 * 获取表格的内容
	 * 
	 * @param sheet
	 * @return
	 */
	private List readData(Sheet sheet) {
		// TODO Auto-generated method stub
		List<HashMap> sheetList = new ArrayList<HashMap>();
		for (int i = 1; i < sheet.getLastRowNum(); i++) {
			HashMap map = new HashMap();
			int j = 0;
			int nullCount = 0;
			String stuId = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(stuId)) {
				map.put("stuId", stuId);
			} else {
				nullCount++;
			}
			String stuName = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(stuName)) {
				map.put("stuName", stuName);
			} else {
				nullCount++;
			}
			/*
			 * String unitId = ExcelUtil.getCellValue(sheet, j++, i); if
			 * (!ExcelUtil.isNullOrEmpty(unitId)) { map.put("unitId", unitId); }
			 * else { nullCount++; } String unitName =
			 * ExcelUtil.getCellValue(sheet, j++, i); if
			 * (!ExcelUtil.isNullOrEmpty(unitName)) { map.put("unitName",
			 * unitName); } else { nullCount++; }
			 */
			String officeName = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(officeName)) {
				map.put("officeName", officeName);
			} else {
				nullCount++;
			}
			String bankName = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(bankName)) {
				map.put("bankName", bankName);
			} else {
				nullCount++;
			}
			String bankNo = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(bankNo)) {
				map.put("bankNo", bankNo);
			} else {
				nullCount++;
			}
			String stuTel = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(stuTel)) {
				map.put("stuTel", stuTel);
			} else {
				nullCount++;
			}
			String yearMonth = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(yearMonth)) {
				map.put("yearMonth", yearMonth);
			} else {
				nullCount++;
			}
			String money = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(money)) {
				map.put("money", money);
			} else {
				nullCount++;
			}
			String beizhu = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(beizhu)) {
				map.put("beizhu", beizhu);
			} else {
				nullCount++;
			}
			if (nullCount != j) {
				map.put("row", Integer.valueOf(i + 1));// 第多少行
				sheetList.add(map);
			}
		}
		return sheetList;
	}

	/**
	 * 检查上传的excel文件的格式（表头）的正确性
	 * 
	 * @param sheet
	 * @return
	 */
	private String checkGeShi(Sheet sheet) {
		String message = null;
		int j = 0;
		String one = ExcelUtil.getCellValue(sheet, j++, 0);
		if (!"助管编号".equals(one)) {
			message = "第" + j + "列必须为助管编号";
			return message;
		}
		String two = ExcelUtil.getCellValue(sheet, j++, 0);
		if (!"姓名".equals(two)) {
			message = "第" + j + "列必须为姓名";
			return message;
		}
		/*
		 * String three = ExcelUtil.getCellValue(sheet, 2, 0); if
		 * (!"单位编号".equals(three)) { message = "第3列必须为单位编号"; return message; }
		 * String four = ExcelUtil.getCellValue(sheet, 3, 0); if
		 * (!"单位名称".equals(four)) { message = "第4列必须为单位名称"; return message; }
		 */
		String five = ExcelUtil.getCellValue(sheet, j++, 0);
		if (!"科室名称".equals(five)) {
			message = "第" + j + "列必须为科室名称";
			return message;
		}
		String six = ExcelUtil.getCellValue(sheet, j++, 0);
		if (!"银行名称".equals(six)) {
			message = "第" + j + "列必须为银行";
			return message;
		}
		String seven = ExcelUtil.getCellValue(sheet, j++, 0);
		if (!"银行卡号".equals(seven)) {
			message = "第" + j + "列必须为姓名";
			return message;
		}
		String eight = ExcelUtil.getCellValue(sheet, j++, 0);
		if (!"联系电话".equals(eight)) {
			message = "第" + j + "列必须为联系电话";
			return message;
		}
		String nine = ExcelUtil.getCellValue(sheet, j++, 0);
		if (!"申请年月".equals(nine)) {
			message = "第" + j + "列必须为申请年月";
			return message;
		}
		String ten = ExcelUtil.getCellValue(sheet, j++, 0);
		if (!"补助金额".equals(ten)) {
			message = "第" + j + "列必须为补助金额";
			return message;
		}
		String eleven = ExcelUtil.getCellValue(sheet, j++, 0);
		if (!"备注".equals(eleven)) {
			message = "第" + j + "列必须为备注";
			return message;
		}
		return null;
	}

}
